package com.centaline.androidsalesblog.activities.entrust;


import android.content.Intent;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.sale.RentDetailActivity;
import com.centaline.androidsalesblog.activities.sale.SaleDetailActivity;
import com.centaline.androidsalesblog.adapter.ConsultAdapter;
import com.centaline.androidsalesblog.adapter.EntrustOriginAdapter;
import com.centaline.androidsalesblog.api.sale.PostListApi;
import com.centaline.androidsalesblog.api.sale.StaffCestApi;
import com.centaline.androidsalesblog.api.usercenter.UpdateReservationApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.ReservePosition;
import com.centaline.androidsalesblog.events.ReserveUpdate;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.databaseobject.PostDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.PostListRo;
import com.centaline.androidsalesblog.model.responseobject.ReservationUserCenterRo;
import com.centaline.androidsalesblog.model.responseobject.StaffListRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.widgets.FixListView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.glide.RoundImageViewTarget;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 预约看房
 */
public class EditReservationActivity extends BaseActivity implements View.OnClickListener {

    private AppCompatEditText aet_name;//称呼
    private AppCompatTextView atv_mobile, atv_staff_name, atv_department, atv_reserve_num;
    private RelativeLayout rl_act_contact;
    private ImageView img_staff;
    private RecyclerView rv_staffs;
    private FixListView flv_list;
    private Button btn_confirm;

    private BitmapTypeRequest<String> mBitmapTypeRequest;
    private DrawableRequestBuilder<String> requestBuilder;
    private ArrayList<StaffDo> staffDos = new ArrayList<>();
    private ConsultAdapter consultAdapter;

    private EntrustOriginAdapter entrustOriginAdapter;
    private ArrayList<PostDo> postDoList = new ArrayList<>();

    private String nickName, phone;
    private ArrayList<Integer> reserveIDList;  //获取约看标识集合
    private StaffDo currentStaffDo;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_edit_reserve;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar("预约看房");
        aet_name = (AppCompatEditText) findViewById(R.id.aet_name);
        rl_act_contact = (RelativeLayout) findViewById(R.id.rl_act_contact);
        atv_mobile = (AppCompatTextView) findViewById(R.id.atv_mobile);
        img_staff = (ImageView) findViewById(R.id.img_staff);
        atv_staff_name = (AppCompatTextView) findViewById(R.id.atv_staff_name);
        atv_department = (AppCompatTextView) findViewById(R.id.atv_department);
        rv_staffs = (RecyclerView) findViewById(R.id.rv_staffs);
        atv_reserve_num = (AppCompatTextView) findViewById(R.id.atv_reserve_num);
        flv_list = (FixListView) findViewById(R.id.flv_list);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    protected void initViews() {

        String cestCodes = getIntent().getStringExtra(ExtraConstant.CestCodes);
        String postIds = getIntent().getStringExtra(ExtraConstant.PostId);
        reserveIDList = getIntent().getIntegerArrayListExtra(ExtraConstant.ReserveIDList);
        atv_reserve_num.setText(String.format(Locale.CHINA, "委托房源  (%d)", reserveIDList.size()));

        mBitmapTypeRequest = GlideLoad.initRound(this);
        requestBuilder = GlideLoad.init(this);
        rv_staffs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rv_staffs.setHasFixedSize(true);

        consultAdapter = new ConsultAdapter(this, staffDos, new RecyclerViewItemOnClickListener<StaffDo>() {
            @Override
            public void onItemOnClick(StaffDo staffDo, int tag) {
                setCurrentStaff(staffDo);
            }
        });
        consultAdapter.setRequestBuilder(GlideLoad.initRound(this));
        rv_staffs.setAdapter(consultAdapter);

        entrustOriginAdapter = new EntrustOriginAdapter(this, requestBuilder, postDoList);
        flv_list.setAdapter(entrustOriginAdapter);
        flv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PostDo postDo = postDoList.get(position);
                if ("s".equalsIgnoreCase(postDo.getPostType())) {
                    //二手房
                    startActivity(new Intent(EditReservationActivity.this, SaleDetailActivity.class)
                            .putExtra(ExtraConstant.PostId, postDo.getPostId()));
                } else {
                    //租房
                    startActivity(new Intent(EditReservationActivity.this, RentDetailActivity.class)
                            .putExtra(ExtraConstant.PostId, postDo.getPostId()));
                }
            }
        });

        btn_confirm.setOnClickListener(this);
        rl_act_contact.setOnClickListener(this);

        userInfo();
        requestStaffs(cestCodes);
        requestPostList(postIds);
    }

    private void requestPostList(String ids) {
        PostListApi postListApi = new PostListApi(EditReservationActivity.class, PostListRo.class,
                new IResponseListener<PostListRo>() {
                    @Override
                    public void onResponse(PostListRo postListRo) {
                        postDoList.clear();
                        postDoList.addAll(postListRo.getList());
                        entrustOriginAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        postListApi.setPostIds(ids);
        postListApi.startRequest();
    }

    private void requestStaffs(String CestCodes) {
        StaffCestApi staffCestApi = new StaffCestApi(EditReservationActivity.class, StaffListRo.class,
                new IResponseListener<StaffListRo>() {
                    @Override
                    public void onResponse(StaffListRo staffListRo) {
                        staffDos.clear();
                        staffDos.addAll(staffListRo.getStaffDos());
                        consultAdapter.notifyDataSetChanged();
                        setCurrentStaff(staffDos.get(0));
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        staffCestApi.setCestcodes(CestCodes);
        staffCestApi.startRequest();
    }

    /**
     * 设置当前的Staff信息
     */
    private void setCurrentStaff(StaffDo staffDo) {
        currentStaffDo = staffDo;
        if (staffDo != null) {
            atv_staff_name.setText(staffDo.getCnName());
            atv_department.setText(staffDo.getDepartmentName());
            if (GlideLoad.needLoad(true)) {
                mBitmapTypeRequest
                        .load(staffDo.getImgUrl())
                        .placeholder(R.drawable.ic_staff_default)
                        .error(R.drawable.ic_staff_default)
                        .centerCrop()
                        .into(new RoundImageViewTarget(img_staff));
            } else {
                mBitmapTypeRequest
                        .load("")
                        .placeholder(R.drawable.ic_staff_default)
                        .error(R.drawable.ic_staff_default)
                        .centerCrop()
                        .into(new RoundImageViewTarget(img_staff));
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm:
                showLoadingDialog();
                UpdateReservationApi updateReservationApi = new UpdateReservationApi(EditReservationActivity.class,
                        ReservationUserCenterRo.class, new IResponseListener<ReservationUserCenterRo>() {
                    @Override
                    public void onResponse(ReservationUserCenterRo reservationUserCenterRo) {
                        cancelLoadingDialog();
                        if (0 == reservationUserCenterRo.getResultNo()) {
                            toast("提交约看成功，经纪人会第一时间联系您");
                            EventBus.getDefault().post(new ReserveUpdate(-1));
                            EventBus.getDefault().post(new ReservePosition(1));
                            finish();
                        } else {
                            snack(reservationUserCenterRo.getMessage());
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        netWorkUnable();
                    }
                });
                updateReservationApi.setCustomerMobile(phone);
                updateReservationApi.setCustomerName(aet_name.getText().toString());
                updateReservationApi.setReserveIDList(reserveIDList);
                updateReservationApi.setStaffName(currentStaffDo.getCnName());
                updateReservationApi.setStaffNo(currentStaffDo.getStaffNo());
                updateReservationApi.startRequest();
                break;
            case R.id.rl_act_contact:
                startActivityForResult(new Intent(this, ModifyPhoneActivity.class), CommonConstant.REQ_MODIFY_MOBILE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_MODIFY_MOBILE:
                    phone = data.getStringExtra(ExtraConstant.Phone);
                    atv_mobile.setText(phone);
                    break;
                default:
                    break;
            }
        }
    }

    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        nickName = userDo.getNickName();
                        phone = userDo.getPhone();
                        aet_name.setText(nickName);
                        atv_mobile.setText(phone);
                    }
                });
    }
}
